import { createRouter, createWebHistory } from 'vue-router'
import { clearPendingSet } from '@/lib/axios'
import NProgress from 'nprogress'
import routes from './routes'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_BASE_PATH),
  routes,
})
const whiteList = ['/login', '/401', '/404', '/500'] //白名单

router.beforeEach(to => {
  const { isLogin } = storeToRefs(useUserStore())
  clearPendingSet() //切换页面时清空请求集合

  if (!NProgress.isStarted()) {
    NProgress.start()
  }

  if (whiteList.includes(to.path)) return true

  if (!isLogin.value) return '/login'

  return true
})

router.afterEach(() => {
  NProgress.done()
})

export default router
